﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.ServiceModel.Syndication;

namespace YahooFinance
{
    /// <summary>
    /// Returns news items using Yahoo Finance RSS feed
    /// </summary>
    public class YahooRssNewsDataService : INewsDataService
    {
        /// <summary>
        /// Returns a list of news items for the given symbol
        /// </summary>
        /// <param name="symbol"></param>
        /// <returns></returns>
        public IList<NewsItem> GetNewsItemsFromSource(string symbol)
        {
            SyndicationFeed feed = null;
            if (symbol == null) return null;
            string url = "http://feeds.finance.yahoo.com/rss/2.0/headline?s=" + symbol + "&region=US&lang=en-US";
            System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            webRequest.Accept = "text/xml";
            using (System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse())
            using (System.IO.Stream responseStream = webResponse.GetResponseStream())
            {
                XmlReader reader = new XmlTextReader(responseStream);
                feed = SyndicationFeed.Load<SyndicationFeed>(reader);
            }            
            return feed.Items.ToList().ConvertAll(x => new NewsItem { 
                DisplayHeadline = String.Format("{0:d MMM yyyy} - {1}", x.PublishDate, x.Title.Text),
                Headline = x.Title.Text,
                Url = x.Links[0].Uri.ToString(),
                Date = x.PublishDate
            });
        }
    }
}
